package com.boby.homecamera.helper;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;


import static com.boby.lib_common.extens.ExtentionsKt.toast;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.boby.homecamera.service.DisplayControlService;
import com.boby.homecamera.service.IDisplayControl;
import com.boby.lib_common.util.BLog;

import rikka.shizuku.Shizuku;

public class ShizukuHelper {
    private static int REQUESTCODE = 1021;
    private static final String TAG = "ShizukuHelper";
    public  void init(){
        Shizuku.addRequestPermissionResultListener(requestPermissionResultListener);
        startServices();
    }
    public void unInit(){
        Shizuku.removeRequestPermissionResultListener(requestPermissionResultListener);

    }
    private Shizuku.OnRequestPermissionResultListener requestPermissionResultListener = new Shizuku.OnRequestPermissionResultListener() {
        @Override
        public void onRequestPermissionResult(int requestCode, int grantResult) {
            if(REQUESTCODE == requestCode){
                startServices();
            }
        }
    };

    private boolean checkPermission(int code) {
        if (Shizuku.isPreV11()) {
            return false;
        }
        try {
                if (Shizuku.checkSelfPermission() == PERMISSION_GRANTED) {
                return true;
            } else if (Shizuku.shouldShowRequestPermissionRationale()) {
                toast("User denied permission (shouldShowRequestPermissionRationale=true)", Toast.LENGTH_SHORT);
                return false;
            } else {
                Shizuku.requestPermission(code);
                return false;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        return false;
    }
    private final Shizuku.UserServiceArgs userServiceArgs =
            new Shizuku.UserServiceArgs(new ComponentName("com.boby.homecamera", DisplayControlService.class.getName()))
                    .daemon(false)
                    .processNameSuffix("service")
                    .debuggable(true)
                    .version(1);
    private void bindUserService() {
        StringBuilder res = new StringBuilder();
        try {
            if (Shizuku.getVersion() < 10) {
                res.append("requires Shizuku API 10");
            } else {
                Shizuku.bindUserService(userServiceArgs, userServiceConnection);
            }
        } catch (Throwable tr) {
            tr.printStackTrace();
            res.append(tr.toString());
        }
        BLog.d(TAG,res.toString().trim());
    }
    private IDisplayControl displayControl;
    private final ServiceConnection userServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder binder) {
            StringBuilder res = new StringBuilder();
            res.append("onServiceConnected: ").append(componentName.getClassName()).append('\n');
            if (binder != null && binder.pingBinder()) {
                displayControl = IDisplayControl.Stub.asInterface(binder);
//                try {
////                    res.append(service.doSomething());
//                    service.setDisplayPower(0,true);
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                    res.append(Log.getStackTraceString(e));
//                }
            } else {
                res.append("invalid binder for ").append(componentName).append(" received");
            }
           BLog.d(TAG,res.toString().trim());
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            BLog.d(TAG,"onServiceDisconnected: " + componentName.getClassName());
            displayControl = null;
        }
    };

    private void unbindUserService() {
        StringBuilder res = new StringBuilder();
        try {
            if (Shizuku.getVersion() < 10) {
                res.append("requires Shizuku API 10");
            } else {
                Shizuku.unbindUserService(userServiceArgs, userServiceConnection, true);
            }
        } catch (Throwable tr) {
            tr.printStackTrace();
            res.append(tr.toString());
        }
        BLog.d(TAG,res.toString().trim());
    }

    private boolean peekUserService() {
        StringBuilder res = new StringBuilder();
        try {
            if (Shizuku.getVersion() < 12) {
                res.append("requires Shizuku API 12");
            } else {
                int serviceVersion = Shizuku.peekUserService(userServiceArgs, userServiceConnection);
                if (serviceVersion != -1) {
                    res.append("Service is running, version ").append(serviceVersion);
                    BLog.d(TAG,res.toString().trim());
                    return true;
                } else {
                    res.append("Service is not running");
                }
            }
        } catch (Throwable tr) {
            tr.printStackTrace();
            res.append(tr.toString());
        }
        BLog.d(TAG,res.toString().trim());
        return false;
    }
    public void startServices(){

        if(checkPermission(REQUESTCODE)){
           boolean result = peekUserService();
            if (!result) {
                // 没有运行，就 bindUserService
                bindUserService();
            }
        }
    }

    public void setDisplayPower(int displayId, boolean mode){
        try {
            if(displayControl == null){
                return;
            }
            displayControl.setDisplayPower(displayId,mode);
        } catch (RemoteException e) {
            e.printStackTrace();
            BLog.d(TAG,"setDisplayPower "+e.toString());
        }
    }


}
